import { mapState } from "vuex";
export default {
  data () {
    return {
      // 判断用户浏览器是不是手机端
      userAgent: /ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(navigator.userAgent.toLowerCase()),
      // 上传文件请求头
      requestHeader: {
        "jwt-token": localStorage.getItem("token")
      },
      apiUrl: process.env.VUE_APP_API_ROOT,
      passType: [{
        value: '审核通过'
      },
      {
        value: '驳回'
      },
      {
        value: '待审核'
      }
      ],
      statusOptions: [{
        value: "待确认",
        label: "待确认"
      },
      {
        value: "已确认",
        label: "已确认"
      },
      {
        value: "未通过审核",
        label: "未通过审核"
      },
      {
        value: "完成",
        label: "完成"
      }
      ],
      roleList: [{
        value: "超级管理员"
      },
      {
        value: "管理员"
      },
      {
        value: "二代"
      },
      {
        value: "渠道"
      },
      {
        value: "运营"
      },
      {
        value: "财务"
      },
      {
        value: "KA"
      },
      {
        value: "SMB"
      },
      {
        value: "商务助理"
      }
      ],
      fullscreenLoading: false, // 全局loading开关
      // code表
      resCodeTable: {
        101: "成功",
        102: "成功（重复领取礼包/激活码等）",
        201: "参数错误",
        202: "参数缺失",
        203: "请求过于频繁",
        204: "重复请求",
        301: "结果未找到",
        302: "库存已空",
        401: "时间未到",
        402: "时间已过",
        403: "不在时间范围内",
        501: "未知错误",
        502: "数据库更新错误",
        601: "其他错误",
        701: "账号已冻结",
        702: "账号未找到",
        711: "账号余额不足",
        712: "获得条件未达成"
      },
      getRole: localStorage.getItem("role"),
      // 表格高度
      tableHeight: '0'
    };
  },
  filters: {
    moneyFormat (m) {
      return (m * 0.01).toFixed(2);
    },
    accountFormat (a) {
      let start = a.indexOf(".");
      if (start != -1) {
        return a.slice(0, start);
      }
      return a;
    }
  },
  methods: {
    // 处理 tableHeight
    getCurrentScreen () {
      // let height = window.screen.availHeight;  // 当前屏幕高度
      let height = document.documentElement.clientHeight; // 当前浏览器窗口可视高度
      if (height <= 900) {
        this.tableHeight = '480';
      } else if (height <= 1200) {
        this.tableHeight = '700';
      } else if (height <= 1500) {
        this.tableHeight = '950';
      }
    },
    deepClone (obj) {
      let _tmp = JSON.stringify(obj);//将对象转换为json字符串形式
      let result = JSON.parse(_tmp);//将转换而来的字符串转换为原生js对象
      return result;
    },
    // 按照属性值大小进行降序排序
    compare (prop) {
      return function (a, b) {
        let val1 = a[prop]
        let val2 = b[prop]
        return val2 - val1
      }
    },
    // 分页 设置当前页面数据
    setCurrentPageData (tableData, currentPage, pageSize) {
      let page = currentPage || 1
      let size = pageSize || 7
      let begin = (page - 1) * size
      let end = page * size
      return tableData.slice(begin, end)
    },
    // 获取指定时间的结果
    getIndexDay (num, sDate) {
      // num 为正数则指定多少天之前
      let now = sDate || new Date();
      let eDay = new Date(now.getTime() - num * 24 * 3600 * 1000);
      let eyear = eDay.getFullYear();
      let emonth = eDay.getMonth() + 1;
      let eday = eDay.getDate();
      if (emonth == 0) {
        emonth = 12;
        eyear = eyear - 1;
      }
      if (emonth < 10) {
        emonth = "0" + emonth;
      }
      if (eday < 10) {
        eday = "0" + eday;
      }
      return eyear + "-" + emonth + "-" + eday;
    },
    // 获取url参数
    getQueryVariable (o, v) {
      let query = window.location.search.substring(1);
      let vars = query.split("&");
      for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split("=");
        if (pair[0] == v) {
          return pair[1];
        }
      }
      return false;
    },
    // 禁止滚轮
    stopScrollFun (evt) {
      evt = evt || window.event;
      if (evt.preventDefault) {
        // Firefox
        evt.preventDefault();
        evt.stopPropagation();
      } else {
        // IE
        evt.cancelBubble = true;
        evt.returnValue = false;
      }
      return false;
    },
    // 格式化传递过来的时间 ， 附带时分秒
    toDateTime (date) {
      const nowDate = date;
      const y = nowDate.getFullYear();
      let m = nowDate.getMonth() + 1;
      m = m < 10 ? `0${m}` : m;
      let d = nowDate.getDate();
      d = d < 10 ? `0${d}` : d;
      let h = nowDate.getHours();
      h = h < 10 ? `0${h}` : h;
      let min = nowDate.getMinutes();
      min = min < 10 ? `0${min}` : min;
      let s = nowDate.getSeconds();
      s = s < 10 ? `0${s}` : s;
      return `${y}-${m}-${d} ${h}:${min}:${s}`;
    },
    // 格式化传递过来的时间
    toDate (date) {
      const nowDate = date;
      const y = nowDate.getFullYear();
      let m = nowDate.getMonth() + 1;
      m = m < 10 ? `0${m}` : m;
      let d = nowDate.getDate();
      d = d < 10 ? `0${d}` : d;
      return `${y}-${m}-${d}`;
    },
    // excel格式
    tableToExcel (excel, fileName) {
      let excelFile =
        "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";
      excelFile +=
        '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
      excelFile +=
        '<meta http-equiv="content-type" content="application/vnd.ms-excel';
      excelFile += '; charset=UTF-8">';
      excelFile += "<head>";
      excelFile += "<!--[if gte mso 9]>";
      excelFile += "<xml>";
      excelFile += "<x:ExcelWorkbook>";
      excelFile += "<x:ExcelWorksheets>";
      excelFile += "<x:ExcelWorksheet>";
      excelFile += "<x:Name>";
      excelFile += "{worksheet}";
      excelFile += "</x:Name>";
      excelFile += "<x:WorksheetOptions>";
      excelFile += "<x:DisplayGridlines/>";
      excelFile += "</x:WorksheetOptions>";
      excelFile += "</x:ExcelWorksheet>";
      excelFile += "</x:ExcelWorksheets>";
      excelFile += "</x:ExcelWorkbook>";
      excelFile += "</xml>";
      excelFile += "<![endif]-->";
      excelFile += "</head>";
      excelFile += "<body>";
      excelFile += excel;
      excelFile += "</body>";
      excelFile += "</html>";
      let uri =
        "data:application/vnd.ms-excel;charset=utf-8," +
        encodeURIComponent(excelFile);
      let link = document.createElement("a");
      link.href = uri;
      link.style = "visibility:hidden";
      link.download = fileName + ".xls";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // table鼠标点击滚动
    tableScroll () {
      var oDivList = document.getElementsByClassName('is-scrolling-left')
      if (oDivList.length > 0) {
        var oDiv = document.getElementsByClassName('is-scrolling-left')[0]
        if (oDiv) {
          var distX = 0;
          var distY = 0;
          oDiv.onmousedown = function (ev) {
            var number = 0
            var oEvent = ev || event;
            distX = oEvent.clientX + oDiv.scrollLeft;
            document.onmousemove = function (ev) {
              var oEvent = ev || event;
              var x = distX - oEvent.clientX;
              oDiv.scrollLeft = x
            }
            document.onmouseup = function () {
              document.onmousemove = null;
              document.onmouseup = null;
            }
          }
        }
      }

    },
    cellClick () {
      var list = document.getElementsByClassName('cell')
      var self = this
      if (list.length > 0) {
        for (var i in list) {
          list[i].onclick = function () {
            if (this.querySelector('button') || this.innerText.includes('去评分') || this.innerText.includes('满意度')) {
            } else {
              document.getElementById('copy_content').innerText = this.innerText
              self.$nextTick(() => {
                const range = document.createRange();
                range.selectNode(document.getElementById('copy_content'));
                const selection = window.getSelection();
                if (selection.rangeCount > 0) selection.removeAllRanges();
                selection.addRange(range);
                document.execCommand('copy');
              })
            }
          };
        }
      }
    },
  },
  computed: {
    ...mapState({
      userInfo: state => {
        state.userInfo.userInfo
      },
      power: state => {
        if (state.userInfo.power.items) {
          return state.userInfo.power.items.map(o => {
            return {
              key: o.ep_privilege_id,
              label: o.source_desc + "-" + o.desc
            };
          });
        }
      },
      userRole: state => state.userInfo.userInfo.items[0].role,
      power_user: state => {
        if (state.userInfo.power_user.items) {
          return state.userInfo.power_user.items.map(o => {
            return o.endpoint_method;
          });
        }
      },
      fresh: state => state.userInfo.fresh
    }),
    homePower () {
      let role = ["danny", "wangchao", "lxy", 'shengjingyin', 'dwn'];
      return role.find((item) => this.getRole == item) ? true : false;
    }
  },
  mounted () {
  },
  filters: {
    formatMoney (num) {
      return (num * 1).toFixed(0).replace(/(\d)(?=(?:\d{3})+$)/g, "$1,")
    },
    formatTime (v) {
      return v.replace(/T/, ' - ');
    },
  }
};